//
//  ShopAddViewCtrl.m
//  howcan
//
//  Created by apple on 4/14/12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "ShopAddViewCtrl.h"
// #import "UneedGet2Api.h"
#import "JSONKit.h"
#import "MapViewCtrl.h"
#import "howcanApi2Get.h"

#define API_GetAreas  @"100"
#define API_GetCategorys  @"101"
#define API_PostShopAdd @"102"


@implementation ShopAddViewCtrl

@synthesize inputTexts;
@synthesize thePickerView;
@synthesize allPickers,mainPickers,detailPickers;
@synthesize actionSheet;
@synthesize categorys;
@synthesize areas;
@synthesize shop_lat,shop_lng;
@synthesize api2gets;

- (void)dealloc {
	[api2gets release];
	api2gets = nil;
	[areas release];
	[categorys release];
	[actionSheet release];
	[detailPickers release];
	[mainPickers release];
	[allPickers release];
	[thePickerView release];
	[inputTexts release];
    [super dealloc];
}


- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
	style = UITableViewStyleGrouped;
    if (self = [super initWithStyle:style]) {
    }
    return self;
}


- (NSMutableDictionary *)setInputItemWithTitle:(NSString*)title withInputHint:(NSString *)inputhint
								   withCount:(NSString *)count withFormId:(NSString *)formid {
	NSMutableDictionary *inputdic = [[[NSMutableDictionary alloc] init]autorelease];
	[inputdic setObject:title forKey:@"title"];
	[inputdic setObject:inputhint forKey:@"inputhint"];
	[inputdic setObject:count forKey:@"count"];
	[inputdic setObject:formid forKey:@"formid"];
	[inputdic setObject:@"" forKey:@"inputtext"];
	return inputdic;	
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
	inputTexts = [[NSMutableArray alloc]init];
	NSMutableArray *_group_1 = [[NSMutableArray alloc]init];

	[_group_1 addObject:[self setInputItemWithTitle:@"名称"
										withInputHint:@"请填写商家名称" 
											withCount:@""
										   withFormId:@"t_item[name]" ]];

	[_group_1 addObject:[self setInputItemWithTitle:@"分店"
										 withInputHint:@"选填: 如有分店名称请填写" 
											 withCount:@""
											withFormId:@"t_item[subname]" ]];

	[_group_1 addObject:[self setInputItemWithTitle:@"地区"
									  withInputHint:@""
										  withCount:@"请选择所在地区" 
										 withFormId:@"t_item[aid]" ]];
	
	[_group_1 addObject:[self setInputItemWithTitle:@"类型"
										  withInputHint:@""
											  withCount:@"请选择商家类型" 
											 withFormId:@"t_item[catid]" ]];
	   [_group_1 addObject:[self setInputItemWithTitle:@"地址"
										   withInputHint:@"请填写商家地址" 
											   withCount:@""
											  withFormId:@"t_item[video]" ]];
		[_group_1 addObject:[self setInputItemWithTitle:@"电话"
											withInputHint:@"请填写商家联系电话" 
												withCount:@""
											   withFormId:@"t_item[c_phone]" ]];
	
	[inputTexts addObject:_group_1];
	[_group_1 release];

	NSMutableArray *_group_2 = [[NSMutableArray alloc]init];

	[_group_2 addObject:[self setInputItemWithTitle:@"地图"
									withInputHint:@""
										withCount:@"标注" 
									   withFormId:@"t_item[mappoint]" ]];
	
	[inputTexts addObject:_group_2];
	[_group_2 release];
	

//	[inputTexts setObject:_group];

	
//	NSArray *_main = [[NSArray alloc] initWithObjects:@"美食",@"购物",nil];
//	self.mainCategorys = _main;
//	[_main release];
//	
//	NSArray *_detail = [[NSArray alloc] initWithObjects:@"早点",@"夜宵",@"川菜",nil];
//	self.detailCategorys = _detail;
	
//	[_detail release];
	allPickers = [[NSMutableArray alloc]init];
	mainPickers = [[NSMutableArray alloc]init];
	detailPickers = [[NSMutableArray alloc]init];
	
	categorys = [[NSMutableArray alloc]init];
	if ([categorys count]==0) {
		
		howcanApi2Get *_api_get = [api2gets objectForKey:API_GetCategorys];
		if (_api_get==nil) {
			_api_get = [[howcanApi2Get alloc]init];
			[api2gets setObject:_api_get forKey:API_GetCategorys];
		}
		
		[_api_get getCategorys:self withIndex:API_GetCategorys];
		
		//	[UneedGet2Api getCategorys:self withIndex:0];
	}
	areas = [[NSMutableArray alloc]init];
	if ([areas count]==0) {	
		howcanApi2Get *_api_get = [api2gets objectForKey:API_GetAreas];
		if (_api_get==nil) {
			_api_get = [[howcanApi2Get alloc]init];
			[api2gets setObject:_api_get forKey:API_GetAreas];
		}
		
		[_api_get getAreas:self withIndex:API_GetAreas];
		
//		[UneedGet2Api getAreas:self withIndex:1];

	}
}



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

	NSUserDefaults *_userdef = [NSUserDefaults standardUserDefaults];
	NSString *_mapPoint = [_userdef objectForKey:@"shopMapPoint"];
	NSArray *_mapPoints = [_mapPoint componentsSeparatedByString:@","];
	if ([_mapPoints count]>1) {
		float _map_lat = [[_mapPoints objectAtIndex:1] floatValue] ;
		float _map_lng = [[_mapPoints objectAtIndex:0] floatValue];
		if (_map_lat!=0 || _map_lng!=0) {
			[[[inputTexts objectAtIndex:1] objectAtIndex:0] setObject:_mapPoint forKey:@"inputtext"];
			[[[inputTexts objectAtIndex:1] objectAtIndex:0] setObject:@"已标注" forKey:@"count"];

		}
	}
		//	self.title = _mapPoint;
//	if (![_mapPoint isEqual:@"0,0"]) {
//		
//	}
}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return [inputTexts count] + 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section < [inputTexts count])
		return [[inputTexts objectAtIndex:section] count];
	else return 1;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"inputCell"];
    if( cell == nil)
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"inputCell"] autorelease];   
	
	if ([inputTexts count]<=indexPath.section) {
		
		UILabel *_act_label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 292, 30)];
		_act_label.text = @"添 加";
		_act_label.textColor = [UIColor whiteColor];
		_act_label.backgroundColor = [UIColor clearColor];
		_act_label.textAlignment = UITextAlignmentCenter;
		cell.accessoryView = _act_label;
		cell.backgroundColor = [UIColor blueColor];
		[_act_label release];
		cell.selectionStyle = UITableViewCellSelectionStyleNone;

		return cell;
	}
	
	cell.backgroundColor = [UIColor whiteColor];
	cell.textLabel.textAlignment = UITextAlignmentLeft;
    cell.textLabel.text = [[[inputTexts objectAtIndex:indexPath.section]  objectAtIndex:indexPath.row] objectForKey:@"title"];
	
	if ([[[inputTexts objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"inputhint"]!=@"") {
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 0, 220, 21)];
        textField.placeholder = [[[inputTexts objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"inputhint"];
//		[[inputTexts objectAtIndex:indexPath.row]is
		NSString *_inputtext = [[[inputTexts objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"inputtext"];
		if (_inputtext!=nil) textField.text = _inputtext;
		textField.tag = indexPath.row;
        textField.delegate = self;
//		[textField addTarget:self action:@selector(textFieldWithText:) forControlEvents:UIControlEventEditingChanged];
        cell.accessoryView = textField;
        [textField release];
//		cell.detailTextLabel.text = @"* ";
//		cell.detailTextLabel.textColor = [UIColor redColor];
	} else if ([[[inputTexts objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"count"]!=@"" ) {

//        UILabel *countLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 21)];
//		countLabel.text = [[inputTexts objectAtIndex:indexPath.row] objectForKey:@"count"];
//		[countLabel sizeToFit];
//		cell.accessoryView = countLabel;
//		[countLabel release];
		cell.detailTextLabel.text = [[[inputTexts objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"count"];
		cell.detailTextLabel.textColor = [UIColor grayColor];
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.accessoryView = nil;
	} else {
		cell.accessoryView = nil;
	}
	
/*
	UIButton *_act_btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];

//	UIButton *_act_btn = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 200, 30)]; 
	
//	_act_btn.buttonType = UIButtonTypeRoundedRect;
	_act_btn.frame = CGRectMake(_act_btn.frame.origin.x, _act_btn.frame.origin.y+50, _act_btn.frame.size.width, _act_btn.frame.size.height);
	_act_btn.backgroundColor = [UIColor greenColor];
//	[UIButton buttonWithType:UIButtonTypeRoundedRect];
	[_act_btn setTitle:@"添加" forState:UIControlStateNormal];
	
	self.tableView.tableFooterView = _act_btn; 
//	self.tableView.tableFooterView.frame = CGRectMake(10, 10, 300, 80);
*/
	
	cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;   
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
	
	if (indexPath.section >= [inputTexts count]) {
		if (indexPath.section == [inputTexts count]) {
			NSMutableDictionary *_forms = [[NSMutableDictionary alloc]init]; 
			for (int i=0;i<[inputTexts count];i++) {
				for(int j=0;j<[[inputTexts objectAtIndex:i] count];j++) {
					if ([[[[inputTexts objectAtIndex:i]objectAtIndex:j]objectForKey:@"formid"]length]>0) {
						[_forms setObject:[[[inputTexts objectAtIndex:i]objectAtIndex:j]objectForKey:@"inputtext"]
								   forKey:[[[inputTexts objectAtIndex:i]objectAtIndex:j]objectForKey:@"formid"]];
					}					
				
				}
			}
			[_forms setObject:@"YES"
						   forKey:@"dosubmit"];
			[_forms setObject:@"dsfs"
					   forKey:@"t_item[content]"];
			[_forms setObject:@"12345"
					   forKey:@"t_item[description]"];
			[_forms setObject:@"234"
					   forKey:@"t_item[c_cross]"];
			
			howcanApi2Get *_api_get = [api2gets objectForKey:API_PostShopAdd];
			if (_api_get==nil) {
				_api_get = [[howcanApi2Get alloc]init];
				[api2gets setObject:_api_get forKey:API_PostShopAdd];
			}
			
			[_api_get postShopAdd:_forms withDelegate:self withIndex:API_PostShopAdd];
			
//			[UneedGet2Api postShopAdd:_forms withDelegate:self withIndex:3];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hello"
                                                            message:[NSString stringWithFormat:@"Order: %@", _forms ]
                                                           delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
			[_forms release];
		}
		return;
	}
	
	if ([[[[inputTexts objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"title"] isEqual:@"地图"]) {
		MapViewCtrl *_mapViewCtrl = [[MapViewCtrl alloc]init];
		_mapViewCtrl.title = [NSString stringWithFormat:@"地图标注"];
		_mapViewCtrl.navigationItem.rightBarButtonItem.enabled = YES;
		_mapViewCtrl.navigationItem.rightBarButtonItem.title =@"标注";
//		_mapViewCtrl.map_lat = [super loc_lat];
//		_mapViewCtrl.map_lng = [super loc_lng];
		_mapViewCtrl.is_edit = YES;
		[self.navigationController pushViewController:_mapViewCtrl animated:YES];
		[_mapViewCtrl release];
		return;
	}
	
	
	
	pickviewtype = 0;	
	if ([[[[inputTexts objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"title"] isEqual:@"类型"]) {
		pickviewtype =1;
	}
	if ([[[[inputTexts objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"title"] isEqual:@"地区"]) {
		pickviewtype =2;
	}
	
//		UIActionSheet *_alert = [[UIActionSheet alloc]initWithTitle:@"请选择商家类型"
//														message:@"\n\n\n\n\n\n\n\n\n"
//													   delegate:self
//											  cancelButtonTitle:@"取消" 
//											  otherButtonTitles:@"确定",nil];
	if (pickviewtype>0) {
		NSString *acttitle = [NSString stringWithFormat:@""];
		if (pickviewtype==1) {
			 acttitle = [NSString stringWithFormat:@"请选择商家类型"];
		}
		if (pickviewtype==2) {
			acttitle = [NSString stringWithFormat:@"请选择地区"];
		}
		
		if (actionSheet==nil) {
			actionSheet = [[UIActionSheet alloc] initWithTitle:acttitle
																 delegate:self 
														cancelButtonTitle:nil 
												   destructiveButtonTitle:nil
														otherButtonTitles:nil];
		actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
		//	actionSheet.destructiveButtonIndex = 1;	// make the second button red (destructive)
		actionSheet.tag = 1;
		}
		
		actionSheet.title = acttitle;
		
		self.thePickerView = [[[UIPickerView alloc]initWithFrame:CGRectMake(0, 40, 320, 500)] autorelease];
		thePickerView.showsSelectionIndicator = YES;
//		_picker.frame = CGRectMake(0, 10, 320, 250);
		thePickerView.delegate = self;
		
//		[pickerView selectRow: value+1 inComponent:0 animated:NO];
//		[categoryPicker selectRowAtIndexPath:[NSIndexPath indexPathForRow:[mainCategorys count]-1 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
		
//		actionSheet.frame = CGRectMake(0, 0, 320, 400);
		
		UIToolbar *_title_bar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 40)];
		_title_bar.barStyle = UIBarStyleBlack;
		UIBarButtonItem *_btn_cancel = [[UIBarButtonItem alloc]
										initWithTitle:@"取消" 
										style:UIBarButtonItemStyleBordered
										target:self 
										action:@selector(act_category_cancel)];
		UIBarButtonItem *seprater	= [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
		UIBarButtonItem *_btn_done = [[UIBarButtonItem alloc]
										initWithTitle:@"确定" 
										style:UIBarButtonItemStyleBordered
										target:self 
									  action:@selector(act_category_done)];
		

//		UIBarButtonItem *_btn_cancel = [[UIBarButtonItem alloc] initWithFrame:CGRectMake(0, 20, 60, 30)];
//		[_btn_cancel setTitle:@"取消"];
		//		_btn_cancel.frame = CGRectMake(10, 10, 100, 30);
//		UIButton *_btn_cancel = [[UIButton alloc]initWithFrame:CGRectMake(0, 20, 60, 30)];
//		[_btn_cancel setTitle:@"取消" forState:UIControlStateNormal];
//		_btn_cancel.enabled = YES;
//		[_title_bar addSubview:_btn_cancel];

		_title_bar.items = [NSArray arrayWithObjects:_btn_cancel, seprater,_btn_done, nil];
		
		[actionSheet addSubview:_title_bar];
//		[_btn_cancel release];
		
		[actionSheet addSubview:thePickerView];
		[actionSheet showInView:self.view]; // show from our table view (pops up in the middle of the table)
		[actionSheet setBounds:CGRectMake(0, 0, 320, 460)];

//		[actionSheet release];
		
//		[_alert addSubview:_picker];
//		[_alert show];
//		[_alert release];
		
		[allPickers removeAllObjects];

		if (pickviewtype == 1) {
			[allPickers addObjectsFromArray:categorys];
			mainPicker_id = mainCategory_id;
			detailPicker_id = detailCategory_id;
		}
		if (pickviewtype == 2) {
			[allPickers addObjectsFromArray:areas];
			mainPicker_id = mainArea_id;
			detailPicker_id = detailArea_id;
		}
		
		[mainPickers removeAllObjects];
		[detailPickers removeAllObjects];
		
		for (int i=0;i<[allPickers count];i++) {
			if ([[[allPickers objectAtIndex:i] objectForKey:@"parentId"] intValue] ==0) {
				[mainPickers addObject:[allPickers objectAtIndex:i]];
			}
			else {
				[detailPickers addObject:[allPickers objectAtIndex:i]];
			}
		}        
		      
		for (int i=0; i<[mainPickers count];i++) {
			if ([[[mainPickers objectAtIndex:i]objectForKey:@"id"]intValue]==mainPicker_id) {
				[thePickerView selectRow:i inComponent:0 animated:YES];
				break;
			}
		}
              
		for (int i=0; i<[detailPickers count];i++) {
			if ([[[detailPickers objectAtIndex:i]objectForKey:@"id"]intValue]==detailPicker_id) {
				[thePickerView selectRow:i inComponent:1 animated:YES];
				break;
			}
		}
        
        if (mainPicker_id==0) {
            [self pickerView:thePickerView didSelectRow:0 inComponent:0];
        }        

        if (detailPicker_id==0) {
            [self pickerView:thePickerView didSelectRow:0 inComponent:1];
        }
        //        if (detailPicker_id==0) [thePickerView selectRow:0 inComponent:1 animated:YES];
		
		
	}
	
	
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    int i_index = textField.tag;
	for (int i=0;i<[inputTexts count];i++) {
		if (i_index < [[inputTexts objectAtIndex:i] count]) {
			[[[inputTexts objectAtIndex:i] objectAtIndex:i_index] setObject:textField.text forKey:@"inputtext"];	
			return YES;
		} else {
			i_index -= [[inputTexts objectAtIndex:i] count]; 
		}
	}
		
    return YES;
}


- (void)act_category_cancel {
	[actionSheet dismissWithClickedButtonIndex:0 animated:YES];	
}

- (void)act_category_done {
	[actionSheet dismissWithClickedButtonIndex:1 animated:YES];

	NSString *_categoryname = [NSString stringWithFormat:@""];
	for (int i=0;i<[mainPickers count];i++) {
		if ([[[mainPickers objectAtIndex:i] objectForKey:@"id"] intValue]==mainPicker_id) {
			_categoryname = [_categoryname  stringByAppendingFormat:@"%@",[[mainPickers objectAtIndex:i]objectForKey:@"name"]];
			break;
		}
	}
	
	for (int i=0;i<[detailPickers count];i++) {
		if ([[[detailPickers objectAtIndex:i] objectForKey:@"id"] intValue]==detailPicker_id) {
			_categoryname = [_categoryname stringByAppendingFormat:@" - %@",[[detailPickers objectAtIndex:i]objectForKey:@"name"]];
			break;
		}
	}
	
	if (pickviewtype==1) {
		[[[inputTexts objectAtIndex:0]objectAtIndex:3] setObject:_categoryname forKey:@"count"];
		[[[inputTexts objectAtIndex:0]objectAtIndex:3] setObject:[NSString stringWithFormat:@"%i",detailPicker_id] forKey:@"inputtext"];
		
		mainCategory_id = mainPicker_id;
		detailCategory_id = detailPicker_id;
	}

	if (pickviewtype==2) {
		[[[inputTexts objectAtIndex:0]objectAtIndex:2] setObject:_categoryname forKey:@"count"];
		[[[inputTexts objectAtIndex:0]objectAtIndex:2] setObject:[NSString stringWithFormat:@"%i",detailPicker_id] forKey:@"inputtext"];

		mainArea_id = mainPicker_id;
		detailArea_id = detailPicker_id;
	}
	
	
	[self.tableView reloadData];
}

#pragma mark -
#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    // the user clicked one of the OK/Cancel buttons
    if (buttonIndex == 0)	// 取消
    {
        //NSLog(@"ok");
    }
    else  // 确定
    {

		
    }
}

#pragma mark -
#pragma mark UIPickerViewDataSource

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString *returnStr = @"";
    
    // note: custom picker doesn't care about titles, it uses custom views
//    if (pickerView == categoryPicker)

        if (component == 0)
        {
            returnStr = [[mainPickers objectAtIndex:row] objectForKey:@"name"];
        }
        else
        {
            returnStr = [[detailPickers objectAtIndex:row] objectForKey:@"name"];
        }
	
    return returnStr;
}

//- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
//{
//    CGFloat componentWidth = 0.0;
//	
//    if (component == 0)
//        componentWidth = 240.0;    // first column size is wider to hold names
//    else
//        componentWidth = 40.0;    // second column is narrower to show numbers
//	
//    return componentWidth;
//}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 40.0;
}

- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated {

}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
	if (component == 0) {
		mainPicker_id = [[[mainPickers objectAtIndex:row] objectForKey:@"id"]intValue];
		[detailPickers removeAllObjects];
		for(int i=0;i<[allPickers count];i++){
			if ([[[allPickers objectAtIndex:i]objectForKey:@"parentId"] intValue]==mainPicker_id) {
				[detailPickers addObject:[allPickers objectAtIndex:i]];
			}
		}
        [pickerView reloadComponent:1];     // 重点在这, 选中上层时, 相应的下层的数据会变动, 此时需要reloadComponent
    }
	if (component == 1) {
		detailPicker_id = [[[detailPickers objectAtIndex:row]objectForKey:@"id"]intValue];		
	}    
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
 
	if (component==0)
		return [mainPickers count];
	else {
		int i_count = 0;
		for (int i=0;i<[detailPickers count];i++) {
			if ([[[detailPickers objectAtIndex:i] objectForKey:@"parentId"] intValue] ==mainPicker_id) {
				i_count++;
			}
		}
		return i_count;
	}
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

/*数据下载完毕 */
-(void)  completedCallback:(NSArray *) data {
	if ([data count]<2) return;
	NSLog(@"data＝＝＝%@",[data objectAtIndex:1]);
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hello"
                                                    message:[NSString stringWithFormat:@"Order: %@", [data objectAtIndex:1] ]
                                                   delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
//	NSUserDefaults *_ud = [NSUserDefaults standardUserDefaults];
	
//	NSString *_cookies = [_ud objectForKey:@"cookies"];
//	NSLog(_cookies);
	NSString *theIndex = [data objectAtIndex:0];
	NSString *_data = [NSString stringWithFormat:@"%@",[data objectAtIndex:1]];
    NSMutableDictionary *jsondic = [_data objectFromJSONString];
	NSNumber *errCode = [jsondic objectForKey:@"errCode"];
	if ([errCode intValue]==0) {	
		if (theIndex==API_GetCategorys) {   // 得到商家类型
			[categorys addObjectsFromArray:[[jsondic objectForKey:@"errMessage"]objectFromJSONString]] ;

		}

		if (theIndex==API_GetAreas) {   // 得到地区
			[areas addObjectsFromArray:[[jsondic objectForKey:@"errMessage"]objectFromJSONString]] ;
		}
		
		
		
		//		[self.tableView reloadData];
	}
    
}

@end

